package com.ushine.web.template.lock.service.impl;

import com.ushine.web.component.exception.ServiceException;
import com.ushine.web.template.lock.service.ILockService;
import com.ushine.web.template.validation.model.ValidationDO;
import com.ushine.web.template.validation.service.IValidationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @Author: yls
 * @Date 2022/4/7 9:48
 * @Description: lock 测试
 * @Version 1.0
 **/
@Slf4j
@Service
public class LockServiceImpl implements ILockService {

    @Resource
    private IValidationService validationService;

    /**
     * 测试id
     */
    private Long id = 1507254454430396418L;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void add(Integer number) throws ServiceException {
        // 业务处理（涉及线程安全的逻辑处理）
        Optional<ValidationDO> validationOptional = validationService.getValidation(id);
        if (validationOptional.isPresent()) {
            ValidationDO validation = validationOptional.get();
            Integer age = validation.getAge();
            log.info("当前线程名称：{}，当前的统计值：{}", Thread.currentThread().getName(), age);
            validation.setAge(validation.getAge() + number);
            validationService.updateValidation(validation);
            log.info("当前线程名称：{}，添加后的统计值：{}", Thread.currentThread().getName(), validation.getAge());
        }
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public void decrease(Integer number) throws ServiceException {
        // 业务处理（涉及线程安全的逻辑处理）
        Optional<ValidationDO> validationOptional = validationService.getValidation(id);
        if (validationOptional.isPresent()) {
            ValidationDO validation = validationOptional.get();
            Integer age = validation.getAge();
            log.info("当前线程名称：{}，当前的统计值：{}", Thread.currentThread().getName(), age);
            validation.setAge(validation.getAge() - number);
            validationService.updateValidation(validation);
            log.info("当前线程名称：{}，减少后的统计值：{}", Thread.currentThread().getName(), validation.getAge());
        }


    }


}
